package com.olympus.hermes.gateway.handler;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * @author mickey
 * @since 2020.08.08
 */
@Component
public class AuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        String path = exchange.getRequest().getURI().toString();

        UriComponents build = UriComponentsBuilder.fromHttpUrl(path)
                .encode()
                .build();
        URI uri = build.toUri();
        ServerHttpRequest request = exchange.getRequest()
                .mutate()
                .uri(uri)
//                .header("Authorization", "Bearer ")
                .build();
        exchange = exchange.mutate().request(request).build();
        return webFilterExchange.getChain().filter(exchange);
    }
}
